/*
 * This code demonstrates how to store and read data on a record of the
 * mobile device's RecordStore.  For more info read the API documentation on
 * the javax.microedition.rms.RecordStore class, and search the web for "j2me
 * RecordStore tutorial" and "j2me RecordStore example".
 *
 * Not much effort was put into making this nice style-wise.
 *
 * (c) Nilton Bila
 */

package recstore;

import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;
import javax.microedition.rms.*;

/**
 * @author nilton
 */
public class RecStore extends MIDlet implements CommandListener {
   public RecStore(){
       String text = "This message is stored in the Record Store.";
       byte data[] = null;
       RecordStore rs;
       Form form = new Form( "Record Store Demo" );

       Display display = Display.getDisplay(this);
       display.setCurrent( form );

       //register exit command
       form.addCommand( new Command("EXIT", Command.EXIT, 1) );
       form.setCommandListener(this);

       //Writing to record store
       try{
          rs = RecordStore.openRecordStore( "mystore", true );
          //only add a new record if there is none
          if( rs.getNextRecordID() == 1){
             rs.addRecord( text.getBytes(), 0, text.length());
          }
          else//otherwise modify existing record
             rs.setRecord( 1, text.getBytes(), 0, text.length());

       }catch( RecordStoreNotOpenException ex){return;}
       catch( RecordStoreException ex){return;}

       //Reading from a RecordStore
       try{
          //get data from record
          data = rs.getRecord( 1 );
          rs.closeRecordStore();  
      }catch( RecordStoreNotOpenException ex){return; }
      catch( RecordStoreException ex){ return; }

      //display data read
      form.append(new String( data ));
   }

   public void startApp() {
   }

   public void pauseApp() {
   }

   public void destroyApp(boolean unconditional) {
   }
   public void commandAction(Command c, Displayable s) {
       if(c.getCommandType() == Command.EXIT){
          destroyApp(false);
          notifyDestroyed();
          }
   }
}
